package com.tsfyun.scm.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.tsfyun.scm.gateway.util.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @Description:
 * @CreateDate: Created in 2020/12/18 13:42
 */
@Slf4j
public class IPWhiteCheckFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String ip = IpUtils.getIpAddress(exchange.getRequest());
        Boolean exists = stringRedisTemplate.hasKey("BLACK_IP:" + ip);
        if(exists){
           log.info("已成功拦截IP【{}】的请求",ip);
           exchange.getResponse().setStatusCode(HttpStatus.OK);
           JSONObject resultJson = new JSONObject();
           resultJson.fluentPut("code",String.valueOf(HttpStatus.FORBIDDEN.value())).fluentPut("message","您暂无权限访问本系统,请稍后重试");
           byte[] bytes = resultJson.toJSONString().getBytes(StandardCharsets.UTF_8);
           exchange.getResponse().getHeaders().add("Content-Type","application/json;charset=UTF-8");
           DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
           return exchange.getResponse().writeWith(Flux.just(buffer));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -900;
    }
}
